<script setup>
import BaseHeader from '@/components/BaseHeader.vue'
import Poppver from '@/components/Poppver.vue'
import { ref, onMounted, watchEffect, onBeforeUnmount } from 'vue'
import { HEART_MESSAGE, WS_BASE_URL } from '@/utils/constant.js'
import { useUserStore } from '@/stores/user'
import { useMessageStore } from '@/stores/unread'
import router from '@/router'
import axiosInstance from '@/utils/request'

const store = useUserStore()
const messageStore = useMessageStore()
const contacts = ref([])
const sysContacts = ref([])
const notifyMsgs = ref([])
const showPopover = ref(false)
const ws = ref(null)

// 获取联系人列表
async function getSessionList(userType) {
  try {
    const response = await axiosInstance.get('/session/list', {
      headers: {
        token: store.token
      },
      params: {
        type: userType
      }
    })
    return response.data.data // 返回异步数据
  } catch (error) {
    console.error('Error:', error)
    throw error
  }
}

const getNotifyMsgList = () => {
  axiosInstance
    .get('/chat-notify-message/session/list', {
      headers: {
        token: store.token
      }
    })
    .then((response) => {
      notifyMsgs.value = response.data.data
    })
    .catch((error) => {
      console.log(error)
    })
}
const connectWebSocket = () => {
  ws.value = new WebSocket(
    WS_BASE_URL + `/ws?token=${store.token}&session=true`
  )

  ws.value.onopen = () => {
    console.log('WebSocket连接已建立......HomePage')
  }

  ws.value.onmessage = (event) => {
    if (event.data === HEART_MESSAGE) {
      // 忽略心跳消息
      console.log('接收到心跳消息......')
      return
    }
    const message = JSON.parse(event.data)
    console.log('接收到消息: ', message)
    if (message.type === 'msgCount') {
      // 判断消息类型
      const msgCount = message.content
      const index = contacts.value.findIndex(
        (contact) => contact.id === msgCount.userId
      )
      if (index != -1) {
        contacts.value[index].unreadMessageCount = msgCount.msgCount
      }
    } else if (message.type === 'notifyCount') {
      const index = notifyMsgs.value.findIndex(
        (notifyMsg) => notifyMsg.sysId === message.sysId
      )
      if (index != -1) {
        notifyMsgs.value[index].count = message.content
      }
    }
    // 更新未读消息数量
    updateUnreadCount()
  }

  ws.value.onclose = () => {
    console.log('WebSocket连接已关闭......HomePage')
  }

  ws.value.onerror = (error) => {
    console.error('WebSocket错误:', error)
  }
}
// 点击联系人
const handleContactClick = (contact) => {
  // 跳转到聊天界面并传递联系人信息
  router.push({
    path: '/chat',
    query: {
      contactId: contact.id,
      contactName: contact.nickname,
      avatar: contact.avatar,
      sessionId: contact.sessionId,
      contactType: 1
    }
  })
}
// 点击Ai联系人
const handleContactAiClick = (contact) => {
  // 跳转到聊天界面并传递联系人信息
  router.push({
    path: '/chat',
    query: {
      contactId: contact.id,
      contactName: contact.nickname,
      avatar: contact.avatar,
      sessionId: contact.sessionId,
      contactType: 2
    }
  })
}
// 获取未读消息整数
const updateUnreadCount = () => {
  let totalUnreadMessages = 0
  let totalUnreadNotifyMessages = 0
  let totalMsg = 0
  watchEffect(() => {
    if (contacts.value !== undefined) {
      totalUnreadMessages = contacts.value.reduce((total, contact) => {
        return total + (contact.unreadMessageCount || 0)
      }, 0)
      console.log('totalUnreadMessages', totalUnreadMessages)
      console.log('contacts:', contacts.value)
    }
    if (notifyMsgs.value !== undefined) {
      totalUnreadNotifyMessages = notifyMsgs.value.reduce(
        (total, notifyMsg) => {
          return total + (notifyMsg.count || 0)
        },
        0
      )
      console.log('notifyMsgs: ', notifyMsgs.value)
      console.log('totalUnreadNotifyMessages', totalUnreadNotifyMessages)
      totalMsg = totalUnreadMessages + totalUnreadNotifyMessages
    }
    console.log('total', totalMsg)
    // 更新 Pinia store 中的未读消息总数
    messageStore.setunreadMessageCount(totalMsg)
  })
}
onMounted(async () => {
  // 建立 WebSocket 连接
  connectWebSocket()
  // 获取联系人会话
  await getSessionList(0).then((data) => (contacts.value = data))
  // 获取系统用户会话
  await getSessionList(1).then((data) => (sysContacts.value = data))
  // 获取消息会话
  getNotifyMsgList()
  // 更新未读的消息数
  updateUnreadCount()
})
onBeforeUnmount(() => {
  if (ws.value) {
    ws.value.close()
  }
})
// 自定义actions
const menuActions = [{ text: '添加好友' }, { text: '创建群聊' }]

// 处理选中的action
const handleActionSelected = (action) => {
  if (action.text === '添加好友') {
    router.push('/search')
  } else if (action.text === '创建群聊') {
    router.push('/createGroup')
  }
}
const handleNotifyClick = (notifyMsg) => {
  router.push({
    path: '/notify',
    query: {
      sysId: notifyMsg.sysId,
      toId: store.user.id
    }
  })
}
</script>

<template>
  <base-header>
    <template #add>
      <Poppver
        :actions="menuActions"
        v-model:showPopover="showPopover"
        @action-selected="handleActionSelected"
      />
    </template>
  </base-header>

  <!-- 系统消息列表 -->
  <div class="notify-list">
    <ul>
      <li
        v-for="notifyMsg in notifyMsgs"
        @click="handleNotifyClick(notifyMsg)"
        class="notify-item"
      >
        <img :src="notifyMsg.avatar" alt="头像" class="avatar" />
        <div class="notify-info">
          <p class="nickname">{{ notifyMsg.nickname }}</p>
        </div>
        <div class="notify-count" v-if="notifyMsg.count > 0">
          {{ notifyMsg.count }}
        </div>
      </li>
    </ul>
  </div>
  <!--  系统联系人-->
  <div class="contact-list">
    <ul>
      <li
        v-for="sysContact in sysContacts"
        :key="sysContact.id"
        class="contact-item"
      >
        <img :src="sysContact.avatar" alt="头像" class="avatar" />
        <div class="contact-info" @click="handleContactAiClick(sysContact)">
          <p class="nickname">{{ sysContact.nickname }}</p>
          <p
            class="online-status"
            style="color: green"
            v-if="sysContact.onlineStatus == 0"
          >
            在线
          </p>
          <p
            class="online-status"
            style="color: gray"
            v-else-if="sysContact.onlineStatus == 1"
          >
            离线
          </p>
        </div>
        <div class="message-count" v-if="sysContact.unreadMessageCount > 0">
          {{ sysContact.unreadMessageCount }}
        </div>
      </li>
    </ul>
  </div>

  <!-- 联系人列表 -->
  <div class="contact-list">
    <ul>
      <li v-for="contact in contacts" :key="contact.id" class="contact-item">
        <img :src="contact.avatar" alt="头像" class="avatar" />
        <div class="contact-info" @click="handleContactClick(contact)">
          <p class="nickname">{{ contact.nickname }}</p>
          <p
            class="online-status"
            style="color: green"
            v-if="contact.onlineStatus == 0"
          >
            在线
          </p>
          <p
            class="online-status"
            style="color: gray"
            v-else-if="contact.onlineStatus == 1"
          >
            离线
          </p>
        </div>
        <div class="message-count" v-if="contact.unreadMessageCount > 0">
          {{ contact.unreadMessageCount }}
        </div>
      </li>
    </ul>
  </div>
  <!--  创建群聊对话框-->
</template>

<style scoped>
.notify-count {
  margin-left: auto; /* 推到右边 */
  background-color: red;
  color: white;
  border-radius: 50%; /* 圆形 */
  width: 15px;
  height: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  font-weight: bold;
}

/* 整体容器样式 */
.notify-list,
.contact-list {
  margin: 2px 0; /* 列表之间的间距 */
  padding: 10px;
  border-radius: 8px;
}

/* 系统消息项样式 */
.notify-info {
  margin-left: 10px; /* 与头像的间距 */
}

.notify-content {
  font-size: 14px;
  color: #555;
}

/* 联系人项样式 */
.notify-item,
.contact-item {
  display: flex;
  align-items: center;
  padding: 10px;
  margin-bottom: 10px; /* 每个联系人之间的间距 */
  border-radius: 8px; /* 圆角 */
  background-color: #f0f0f0; /* 背景颜色 */
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); /* 阴影效果 */
  transition: all 0.3s ease; /* 过渡效果 */
}

.contact-item:hover {
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2); /* 悬停时的阴影效果 */
}

.notify-item:hover {
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%; /* 圆形头像 */
  margin-right: 10px;
}

.contact-info {
  flex-grow: 1; /* 使信息部分占据可用空间 */
}

.nickname {
  font-size: 16px;
  font-weight: bold;
  color: #000;
}

.online-status {
  font-size: 12px;
  color: #888;
}

.message-count {
  width: 15px;
  height: 15px;
  background-color: red;
  color: white;
  border-radius: 50%; /* 圆形 */
  display: flex;
  align-items: center;
  justify-content: center; /* 中心对齐 */
  font-size: 12px; /* 调整字体大小 */
}
</style>
